﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Albatross.WPF.Common {
	public class XmlViewPreference : IViewPreference {
		XmlDocument _doc;
		string _fileName;

		public XmlViewPreference(string name) {
			_fileName = name;
			_doc = new XmlDocument();
			if (File.Exists(name)) {
				_doc.Load(name);
			} else {
				_doc.AppendChild(_doc.CreateElement(Root_ElementName));
			}
		}
		const string Preference_ElementName = "Pref";
		const string Root_ElementName = "Root";
		const string ViewModelType_Attribute = "ViewModelType";
		const string ViewType_Attribute = "ViewType";
		const string Key_Attribute = "Key";


		public string Load(IWorkspaceConstruct construct, string key) {
			foreach (XmlNode node in _doc.DocumentElement.ChildNodes) {
				if (node.NodeType == XmlNodeType.Element && node.Name == Preference_ElementName) {
					XmlElement elem = (XmlElement)node;
					if (elem.GetAttribute(ViewModelType_Attribute) == construct.ViewModelType.AssemblyQualifiedName
						&& elem.GetAttribute(ViewType_Attribute) == construct.ViewType.AssemblyQualifiedName
						&& elem.GetAttribute(Key_Attribute) == key) {
							return elem.InnerText;
					}
				}
			}
			return null;
		}

		public void Save(string data, IWorkspaceConstruct construct, string key) {
			bool found = false;
			foreach (XmlNode node in _doc.DocumentElement.ChildNodes) {
				if (node.NodeType == XmlNodeType.Element && node.Name == Preference_ElementName) {
					XmlElement elem = (XmlElement)node;
					if (elem.GetAttribute(ViewModelType_Attribute) == construct.ViewModelType.AssemblyQualifiedName
						&& elem.GetAttribute(ViewType_Attribute) == construct.ViewType.AssemblyQualifiedName
						&& elem.GetAttribute(Key_Attribute) == key) {
					
						elem.InnerText = data;
						found = true;
						break;
					}
				}
			}
			if (!found) {
				XmlElement elem = _doc.CreateElement(Preference_ElementName);
				XmlAttribute attrib = _doc.CreateAttribute(ViewModelType_Attribute);
				attrib.Value = construct.ViewType.AssemblyQualifiedName;
				elem.Attributes.Append(attrib);

				attrib = _doc.CreateAttribute(ViewType_Attribute);
				attrib.Value = construct.ViewType.AssemblyQualifiedName;
				elem.Attributes.Append(attrib);

				if (!string.IsNullOrEmpty(key)) {
					attrib = _doc.CreateAttribute(Key_Attribute);
					attrib.Value = key;
					elem.Attributes.Append(attrib);
				}
				_doc.DocumentElement.AppendChild(elem);
			}
			_doc.Save(_fileName);
		}
	}
}
